using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.SceneManagement;
using Object = UnityEngine.Object;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance { get; private set; }

    [SerializeField] private GameSO gameSO;

    [SerializeField] private GameOverUI gameOverUI;

    private Bird[] birdList;
    private int index = -1;

    private int pigTotalCount;
    private int pigDeadCount;

    private FollowTarget camerFollowTarget;
    
    private void Awake()
    {
        Instance = this;
        pigDeadCount = 0;
        LoadSelectedLevel();
    }

    private void Start()
    {
        birdList = FindObjectsByType<Bird>(FindObjectsSortMode.None);//通过这个方法获得所有小鸟组件 传入泛型为Bird 排序方式为None
        pigTotalCount = FindObjectsByType<Pig>(FindObjectsSortMode.None).Length;
        camerFollowTarget = Camera.main.GetComponent<FollowTarget>();
        
        LoadNextBird();
    }

    private void LoadSelectedLevel()
    {
        Time.timeScale = 1;
        int mapID = gameSO.selectedMapID;
        int levelID = gameSO.selectedLevelID;

        Object levelPrefab = Resources.Load("Map" + mapID + "/" + "Level" + levelID);//加载

        GameObject.Instantiate(levelPrefab);//实例化
    }

    public void LoadNextBird()
    {
        index++;
        if (index >= birdList.Length)
        {
            GameOver();
        }
        else
        {
            birdList[index].GoStage(Slingshot.Instance.getCenterPosition());//小鸟的上场函数
            camerFollowTarget.setTarget(birdList[index].transform);
        }
    }

    public void OnPigDead()
    {
        pigDeadCount++;
        if (pigDeadCount >= pigTotalCount)
        {
            GameOver();
        }
    }

    private void GameOver()
    {
        int starCount = 0;
        float pigDeadPercent = pigDeadCount * 1.0f / pigTotalCount;
        if (pigDeadPercent > 0.99)
        {
            starCount = 3;
        }else if (pigDeadPercent > 0.66)
        {
            starCount = 2;
        }else if (pigDeadPercent > 0.33f)
        {
            starCount = 1;
        }
        gameOverUI.Show(starCount);
        
        gameSO.UpdateLevel(starCount);//将星星数量更新到gameSO中
    }

    public void OnRestartLevel()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }

    public void LevelList()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
    }
}
